<template>
  <el-dialog v-model:model-value="show" :title="isRowDataEmpty ? '新增商品分类' : '新增子分类'" :destroy-on-close="true" @closed="closed">
    <el-form :model="form" :rules="rules" prop="categoryName" ref="formRef">
      <el-form-item label="上级分类" required v-if="props.row && props.row.categoryName">
        <el-input v-model="props.row.categoryName" :disabled="true"/>
      </el-form-item>
      <el-form-item :label="isRowDataEmpty ? '分类名称' : '子分类'" prop="categoryName">
        <el-input v-model="form.categoryName"  type="text" :show-word-limit="true" maxlength="15"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm(formRef)">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {saveOrUpdateCategory} from "@/api/product";
import {ElMessage} from "element-plus/es";
import {PropType} from "vue";
import {FormInstance} from "element-plus";

const props = defineProps<{
  show: boolean,
  row: any
}>()
const emits = defineEmits<{
  (e: 'update:show', value: boolean): void,
  (e: 'confirmed'): void
}>()

const isRowDataEmpty = computed(() => {
  return !Object.keys(props.row).length
})

const rules = reactive({
  categoryName: {
    required: true,
    message: '请输入分类名称',
    trigger: 'blur'
  }
})

const formRef = ref<FormInstance>()
const form = reactive({
  categoryName: '',
})

const show = computed({
  get() {
    return props.show
  },

  set(val:boolean) {
    return emits('update:show', val)
  }
})


const handleCancel = () => {
  show.value = false
}

const handleConfirm = async (formRef: FormInstance) => {
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      const rs: any = await saveOrUpdateCategory({...form, parentId: props?.row?.id})
      show.value = false
      if (rs.code === 200) {
        ElMessage.success('保存成功')
        emits('confirmed')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const closed = () => {
  form.categoryName = ''
}

onMounted(() => {
  form.categoryName = ''
})

onBeforeUnmount(() => {

})
</script>

<style scoped>

</style>
